import com.plealog.genericapp.api.EZUIStarterListener;
import com.plealog.genericapp.api.log.EZLogger;
import com.plealog.genericapp.api.log.EZLoggerManager;
import com.plealog.genericapp.api.log.EZSingleLineFormatter;
import panel.ApplicationPanel;
import panel.role.texturejsonedit.MapPathConfigurePanel;
import panel.role.texturejsonedit.MaterialTypeConfigurePanel;
import panel.role.xmlgenerate.XmlGeneratePanel;
import session.RoleSession;
import util.BeanManager;

import javax.swing.event.AncestorListener;
import java.awt.*;
import java.io.IOException;

public class ApplicationStarterListener implements EZUIStarterListener {

	@Override
	public void preStart() {
		// 日志初始化
		initLog();

		// 耗时任务
		BeanManager.getBean(XmlGeneratePanel.class);
		BeanManager.getBean(MaterialTypeConfigurePanel.class);
		BeanManager.getBean(MapPathConfigurePanel.class);
	}

	@Override
	public void postStart() {
	}

	@Override
	public void frameDisplayed() {
	}

	private final ApplicationPanel applicationPanel = BeanManager.getBean(ApplicationPanel.class);

	@Override
	public Component getApplicationComponent() {
		return applicationPanel;
	}

	@Override
	public boolean isAboutToQuit() {
		// 退出前还要保存一下数据
		// 更新session数据
		if (BeanManager.getBean(MapPathConfigurePanel.class).isShowing())
			for (AncestorListener l : BeanManager.getBean(MapPathConfigurePanel.class).getAncestorListeners())
				l.ancestorRemoved(null);
		if (BeanManager.getBean(MaterialTypeConfigurePanel.class).isShowing())
			for (AncestorListener l : BeanManager.getBean(MaterialTypeConfigurePanel.class).getAncestorListeners())
				l.ancestorRemoved(null);
		if (BeanManager.getBean(XmlGeneratePanel.class).isShowing())
			for (AncestorListener l : BeanManager.getBean(XmlGeneratePanel.class).getAncestorListeners())
				l.ancestorRemoved(null);


		// session保存到本地
		RoleSession.SAVE_SESSION_DATA();
		return true;
	}

	private static void initLog() {
		EZLoggerManager.enableConsoleLogger(false);
		EZLoggerManager.setFileLoggerFormatter(new EZSingleLineFormatter(true));
		try {
			EZLoggerManager.enableFileLogger("logging.txt", true);
		} catch (IOException e) {
			EZLogger.warn("不能安装文件日志记录器: " + e);
		}
		EZLoggerManager.setLevel(EZLoggerManager.LogLevel.info);
		EZLoggerManager.initialize();
	}
}
